import Client from './base';
import * as qiniu from 'qiniu-js';
import { computeMd5, getFileSuffix } from '../utils';

export default class KodoClient extends Client {
    run(callback) {
        const { file, id } = this;
        const config = this.config;
        const { onProgress, onSuccess, onError } = callback;

        /* "path/to/file_name.ext" */
        const key = `${config.uploadDate}${computeMd5(file)}.${getFileSuffix(file)}`;
        const observable = qiniu.upload(file, key, config.token);

        const observer = {
            complete: (data) => onSuccess({ id, data: { ...data, host: config.host, url: data.key, ispType: 'qiNiu' } }),
            error: (info) => onError({ id, info }),
            next: (progress) => {
                onProgress && onProgress({ id, progress: { percent: progress.total.percent } })
            }
        };

        this.subscription = observable.subscribe(observer);
    }

    abort() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
